package com.blog.utils;

import com.blog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Copyright (C), 2022
 * Author: 苏大大
 * Date: 2022-06-07 20:39
 * FileName: AvatarUtils
 * Description:
 */
@Slf4j
public class AvatarUtils {
    private static final String AVATARPATH=("D:\\workspaceIDEA\\springblog\\blog-service-user\\src\\main\\resources\\static\\img\\user\\avatar\\");
    private static final String HTTP="http://localhost:8001/img/user/avatar/";
    @Resource
    private UserService userService;
    public static String uploadAvatar(MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            //UUIDUtils为工具类，使用它随机生成一串字符（作用：上传图片时给图片名称拼接上去，防止图片名称重复）
            String n = UUIDUtils.create(20);
            String path2 = AVATARPATH +n + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //创建File对象，一会向该路径下上传文件
            File newFile = new File(path2);
            //MultipartFile的方法直接写文件
            file.transferTo(newFile);
            return HTTP+ n +file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        }
        return null;
    }

    public static boolean deleteAvatar(String Avatar){
        //删除上次头像
        String path2 = AVATARPATH + Avatar;
        File newFile = new File(path2);
        if(newFile.exists()) {
            boolean flag = false;
            flag= newFile.delete();
            if(flag){
                log.info("成功删除图片:{}",newFile.getName());
                return true;
            }else{
                log.info("删除失败");
                return false;
            }
        }else{
            log.info("图片不存在，终止操作");
            return false;
        }
    }
    public void deleteFiles() {
        File f = new File(AVATARPATH);//获取路径  F:测试目录
        if (!f.exists()) {
            System.out.println(AVATARPATH + " not exists");//不存在就输出
            return ;
        }

        File[] fa = f.listFiles();//用数组接收
        if(userService == null){
            userService = SpringUtils.getBean(UserService.class);
        }
        List<String> avatarList=userService.queryAvatarAll();
        int status=0;
        for (int i = 0; i < fa.length; i++) {//循环遍历
            File fs = fa[i];//获取数组中的第i个
            status=0;
            for (int j = 0; j < avatarList.size(); j++) {
                if(fs.getName().equals(avatarList.get(j))){
                    status=1;
                }
            }
            if(status==0){
                deleteAvatar(fs.getName());
            }
        }
    }
}
